const { GoogleGenerativeAI } = require('@google/generative-ai')
const config = require('../config')
const modelData = ['gemini-2.5-flash', 'gemini-1.5-pro', 'gemini-1.5-flash']

const genAI = new GoogleGenerativeAI(config.gemini.apiKey)

const model = genAI.getGenerativeModel({ model: modelData[0] })

async function geminiAI (prompt, retries = 3, delay = 2000) {
    for (let i = 0; i < retries; i++) {
        try {
            const result = await model.generateContent(prompt);
            const response = await result.response;
            const text = response.text();
            return text
        } catch (err) {
            if (err.status === 503 && i < retries - 1) {
                console.warn(`Gemini 过载，${delay}ms 后重试...`);
                await new Promise(r => setTimeout(r, delay));
                delay *= 2;
            } else {
                throw err;
            }
        }
    }
}


module.exports = { geminiAI }